/**
 * 企业成员列表表格组件
 */

'use client';

import React from 'react';
import {
  Table,
  Tag,
  Space,
  Button,
  Avatar,
  Tooltip,
  Typography,
  Dropdown,
  Modal,
  message,
} from 'antd';
import {
  UserOutlined,
  MoreOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  MailOutlined,
  PhoneOutlined,
  TeamOutlined,
  CrownOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { Member, MemberQueryParams } from '../types/member';
import { formatDate } from '../utils/date';

const { Text, Paragraph } = Typography;
const { confirm } = Modal;

interface MemberTableProps {
  members: Member[];
  loading?: boolean;
  total?: number;
  current?: number;
  pageSize?: number;
  onPageChange?: (page: number, size?: number) => void;
  onView?: (member: Member) => void;
  onEdit?: (member: Member) => void;
  onDelete?: (member: Member) => void;
  queryParams?: MemberQueryParams;
}

export default function MemberTable({
  members,
  loading = false,
  total = 0,
  current = 1,
  pageSize = 30,
  onPageChange,
  onView,
  onEdit,
  onDelete,
  queryParams,
}: MemberTableProps) {
  const getStatusTag = (status: string) => {
    const statusMap: Record<string, { color: string; text: string }> = {
      active: { color: 'green', text: '激活' },
      inactive: { color: 'red', text: '未激活' },
      pending: { color: 'orange', text: '待激活' },
    };
    const config = statusMap[status] || { color: 'default', text: status };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const getRoleTag = (role: string, isAdmin: boolean) => {
    if (isAdmin) {
      return (
        <Tag color="red" icon={<CrownOutlined />}>
          管理员
        </Tag>
      );
    }
    return <Tag color="blue">{role || '普通成员'}</Tag>;
  };

  const handleDelete = (member: Member) => {
    confirm({
      title: '确认删除成员',
      content: (
        <div>
          <p>确定要删除成员 <strong>{member.display_name || member.name}</strong> 吗？</p>
          <p style={{ color: '#ff4d4f', fontSize: '12px' }}>
            此操作不可恢复，请谨慎操作。
          </p>
        </div>
      ),
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        onDelete?.(member);
      },
    });
  };

  const getActionItems = (member: Member) => [
    {
      key: 'view',
      label: (
        <Space>
          <EyeOutlined />
          查看详情
        </Space>
      ),
      onClick: () => onView?.(member),
    },
    {
      key: 'edit',
      label: (
        <Space>
          <EditOutlined />
          编辑成员
        </Space>
      ),
      onClick: () => onEdit?.(member),
    },
    {
      type: 'divider' as const,
    },
    {
      key: 'delete',
      label: (
        <Space style={{ color: '#ff4d4f' }}>
          <DeleteOutlined />
          删除成员
        </Space>
      ),
      onClick: () => handleDelete(member),
      danger: true,
    },
  ];

  const columns: ColumnsType<Member> = [
    {
      title: '成员信息',
      key: 'member_info',
      width: 280,
      fixed: 'left',
      render: (_, member) => (
        <Space>
          <Avatar
            size={40}
            src={member.avatar}
            icon={<UserOutlined />}
            style={{ backgroundColor: member.avatar ? undefined : '#1890ff' }}
          />
          <div>
            <div>
              <Text strong>{member.display_name || member.name}</Text>
              {member.is_admin && (
                <CrownOutlined
                  style={{ color: '#ff4d4f', marginLeft: 4 }}
                  title="管理员"
                />
              )}
            </div>
            <div style={{ fontSize: '12px', color: '#666' }}>
              @{member.name}
            </div>
            {member.email && (
              <div style={{ fontSize: '12px', color: '#666' }}>
                <MailOutlined style={{ marginRight: 2 }} />
                {member.email}
              </div>
            )}
          </div>
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: string) => getStatusTag(status),
      filters: [
        { text: '激活', value: 'active' },
        { text: '未激活', value: 'inactive' },
        { text: '待激活', value: 'pending' },
      ],
      filteredValue: queryParams?.status ? [queryParams.status] : null,
    },
    {
      title: '角色权限',
      key: 'role',
      width: 120,
      render: (_, member) => (
        <Space direction="vertical" size={2}>
          {getRoleTag(member.role, member.is_admin)}
          {member.department && (
            <Tag icon={<TeamOutlined />} color="default">
              {member.department}
            </Tag>
          )}
        </Space>
      ),
    },
    {
      title: '联系方式',
      key: 'contact',
      width: 180,
      render: (_, member) => (
        <Space direction="vertical" size={2}>
          {member.phone && (
            <Text style={{ fontSize: '12px' }}>
              <PhoneOutlined style={{ marginRight: 4 }} />
              {member.phone}
            </Text>
          )}
          {member.email && (
            <Tooltip title={member.email}>
              <Text
                style={{ fontSize: '12px', maxWidth: 160 }}
                ellipsis
              >
                <MailOutlined style={{ marginRight: 4 }} />
                {member.email}
              </Text>
            </Tooltip>
          )}
        </Space>
      ),
    },
    {
      title: '时间信息',
      key: 'time_info',
      width: 160,
      render: (_, member) => (
        <Space direction="vertical" size={2}>
          <Tooltip title="创建时间">
            <Text style={{ fontSize: '12px' }}>
              <ClockCircleOutlined style={{ marginRight: 4 }} />
              {member.created_at ? formatDate(new Date(member.created_at * 1000)) : '-'}
            </Text>
          </Tooltip>
          {member.last_login_at && (
            <Tooltip title="最后登录">
              <Text style={{ fontSize: '12px', color: '#666' }}>
                最后登录: {formatDate(new Date(member.last_login_at * 1000))}
              </Text>
            </Tooltip>
          )}
        </Space>
      ),
      sorter: true,
      sortOrder:
        queryParams?.sort_by === 'created_at'
          ? queryParams?.sort_order === 'desc'
            ? 'descend'
            : 'ascend'
          : null,
    },
    {
      title: '操作',
      key: 'actions',
      width: 80,
      fixed: 'right',
      render: (_, member) => (
        <Space>
          <Button
            type="text"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => onView?.(member)}
            title="查看详情"
          />
          <Dropdown
            menu={{ items: getActionItems(member) }}
            trigger={['click']}
            placement="bottomRight"
          >
            <Button
              type="text"
              size="small"
              icon={<MoreOutlined />}
              title="更多操作"
            />
          </Dropdown>
        </Space>
      ),
    },
  ];

  return (
    <Table<Member>
      columns={columns}
      dataSource={members}
      loading={loading}
      rowKey="id"
      scroll={{ x: 1000 }}
      size="small"
      pagination={{
        current,
        pageSize,
        total,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: (total, range) =>
          `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`,
        pageSizeOptions: ['10', '20', '30', '50', '100'],
        onChange: onPageChange,
        onShowSizeChange: onPageChange,
      }}
      rowClassName={(record, index) =>
        index % 2 === 0 ? 'table-row-light' : 'table-row-dark'
      }
    />
  );
}